<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>路径OD分析 - Apache ECharts 示例</title>
    <link rel="stylesheet" href="css/style.css?v=1.1">
</head>

<body>
    <div class="navbar">
        <a href="index.html">首页</a>
        <a href="traffic_trend.html">客流趋势分析</a>
        <a href="station_ranking.html">站点客流排行</a>
        <a href="funnel_analysis.html">线路站点客流分析</a>
        <a href="line_comparison.html">线路客流量对比</a>
        <a href="transfer_heatmap.html">换乘热度分析</a>
        <a href="poi_analysis.html">站点周边客流特征</a>
        <a href="anomaly_detection.html">异常客流检测</a>
        <a href="od_analysis.html">路径OD分析</a>
        <a href="stop_frequency_usage_analysis.html">站停频率分析</a>
        <a href="dispatch_suggestion.html">智能调度模型</a>
    </div>
    <div class="page-container">
        <div class="chart-header">
            <h2 class="chart-title">路径OD分析（桑基图）</h2>
            <p class="chart-description">
                此桑基图（Sankey Diagram）展示了乘客在不同站点之间的"起点-终点"（Origin-Destination,
                OD）流动路径和流量大小。每一条流线代表了一定数量的乘客从一个站点移动到另一个站点。通过这种可视化方式，可以清晰地识别出主要的出行流向、热门路径以及潜在的拥堵点，为线路优化和新增服务提供数据支持。
            </p>
        </div>
        <div class="kpi-cards-container">
            <div class="kpi-card">
                <h4>最繁忙OD对</h4>
                <p id="kpi-busiest-od">--</p>
            </div>
            <div class="kpi-card">
                <h4>最大始发站</h4>
                <p id="kpi-top-origin">--</p>
            </div>
            <div class="kpi-card">
                <h4>最大终点站</h4>
                <p id="kpi-top-destination">--</p>
            </div>
            <div class="kpi-card">
                <h4>总OD客流量</h4>
                <p id="kpi-total-flow">--</p>
            </div>
        </div>
        <div id="main" style="width: 100%; height:600px;"></div>
    </div>

    <script src="js/echarts.min.js"></script>
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function () {
            var odAnalysisChart = echarts.init(document.getElementById('main'));

            fetch('/api/traffic/od-analysis')
                .then(response => response.json())
                .then(data => {
                    // --- KPI Card Calculations ---
                    if (data && data.links && data.links.length > 0) {
                        // 1. 总OD客流量 & 最繁忙OD对
                        let totalFlow = 0;
                        let busiestLink = { source: '', target: '', value: 0 };
                        data.links.forEach(link => {
                            totalFlow += link.value;
                            if (link.value > busiestLink.value) {
                                busiestLink = link;
                            }
                        });
                        document.getElementById('kpi-total-flow').textContent = `${totalFlow.toLocaleString()} 人次`;
                        document.getElementById('kpi-busiest-od').textContent = `${busiestLink.source} → ${busiestLink.target}`;


                        // 2. 最大始发站 & 最大终点站
                        const origins = {};
                        const destinations = {};
                        data.links.forEach(link => {
                            origins[link.source] = (origins[link.source] || 0) + link.value;
                            destinations[link.target] = (destinations[link.target] || 0) + link.value;
                        });

                        const topOrigin = Object.entries(origins).sort((a, b) => b[1] - a[1])[0];
                        const topDestination = Object.entries(destinations).sort((a, b) => b[1] - a[1])[0];

                        document.getElementById('kpi-top-origin').textContent = topOrigin[0];
                        document.getElementById('kpi-top-destination').textContent = topDestination[0];
                    }
                    // -of KPI Card Calculations ---

                    var option = {
                        title: {
                            text: '路径OD分析 (桑基图)',
                            subtext: '',
                            left: 'center',
                            textStyle: {
                                color: '#333',
                                fontSize: 20
                            }
                        },
                        tooltip: {
                            trigger: 'item',
                            triggerOn: 'mousemove'
                        },
                        series: [
                            {
                                type: 'sankey',
                                data: data.nodes,
                                links: data.links,
                                focusNodeAdjacency: 'allEdges',
                                itemStyle: {
                                    borderWidth: 1,
                                    borderColor: '#aaa'
                                },
                                lineStyle: {
                                    color: 'gradient',
                                    curveness: 0.5
                                }
                            }
                        ]
                    };
                    odAnalysisChart.setOption(option);
                })
                .catch(error => {
                    console.error('Error fetching OD analysis data:', error);
                    document.getElementById('main').innerText = '数据加载失败，请检查后端服务是否正常。';
                });

            window.addEventListener('resize', function () {
                odAnalysisChart.resize();
            });
        });
    </script>
    <script src="js/common.js"></script>
</body>

</html>